import { useCallback, useEffect, useMemo } from 'react'
import { connect } from 'react-redux';
import useDeepCompareEffect from 'use-deep-compare-effect'
import URI from 'urijs';
import dayjs from 'dayjs';
import { baseURL } from '../../const';
import { bindActionCreators } from 'redux';
import './index.css';
import { h0 } from '../../utils/fp';
import Nav from '../../common/Nav'
import useNav from '../../hooks/useNav.js'
import Header from '../../common/Header'
import List from './component/List'
import Bottom from './component/Bottom'
import {
    setFrom,
    setTo,
    setDepartDate,
    setHighSpeed,
    setSearchParsed,
    setTrainList,
    setTicketTypes,
    setTrainTypes,
    setDepartStations,
    setArriveStations,
    prevDate,
    nextDate,
    toggleOrderType,
    toggleHighSpeed,
    toggleOnlyTickets,
    toggleIsFiltersVisible,
    setCheckedTicketTypes,
    setCheckedTrainTypes,
    setCheckedDepartStations,
    setCheckedArriveStations,
    setDepartTimeStart,
    setDepartTimeEnd,
    setArriveTimeStart,
    setArriveTimeEnd,
} from './store/actionCreators';

function Query(props) {
    const {
        trainList,//车票列表
        from,
        to,
        departDate,
        highSpeed,//是否选择了高铁动车
        searchParsed,//是否解析完成
        dispatch,
        orderType,//排序默认出发早->晚
        onlyTickets,//是否只看有票
        isFiltersVisible,//是否显示隐藏
        ticketTypes,//所有的被选项
        trainTypes,//车次类型
        departStations,//出发车站
        arriveStations,//到达车站
        checkedTicketTypes,//选中类型
        checkedTrainTypes,//选中的车次类型
        checkedDepartStations,//选中出发车站
        checkedArriveStations,//选中的到达车站
        departTimeStart,//出发时间起始点
        departTimeEnd,//出发时间的截止点
        arriveTimeStart,//到达时间的起点
        arriveTimeEnd,//到达时间的截止点
    } = props;
    const onBack = useCallback(() => {
        window.history.back();
    }, []);
    useEffect(() => {
        const queries = URI.parseQuery(window.location.search);
        const { from, to, date, highSpeed } = queries;
        dispatch(setFrom(from));
        dispatch(setTo(to));
        dispatch(setDepartDate(h0(dayjs(date).valueOf())));
        dispatch(setHighSpeed(highSpeed === 'true'));
        dispatch(setSearchParsed(true));
    }, []);
    useDeepCompareEffect(() => {

        if (!searchParsed) {
            return;
        }

        const url = new URI('/rest/query')
            .setSearch('from', from)
            .setSearch('to', to)
            .setSearch('date', dayjs(departDate).format('YYYY-MM-DD'))
            .setSearch('highSpeed', highSpeed)
            .setSearch('orderType', orderType)
            .setSearch('onlyTickets', onlyTickets)
            .setSearch(
                'checkedTicketTypes',
                Object.keys(checkedTicketTypes).join()
            )
            .setSearch(
                'checkedTrainTypes',
                Object.keys(checkedTrainTypes).join()
            )
            .setSearch(
                'checkedDepartStations',
                Object.keys(checkedDepartStations).join()
            )
            .setSearch(
                'checkedArriveStations',
                Object.keys(checkedArriveStations).join()
            )
            .setSearch('departTimeStart', departTimeStart)
            .setSearch('departTimeEnd', departTimeEnd)
            .setSearch('arriveTimeStart', arriveTimeStart)
            .setSearch('arriveTimeEnd', arriveTimeEnd)
            .toString();

        fetch(baseURL + url)
            .then(response => response.json())
            .then(result => {
                const {
                    dataMap: {
                        directTrainInfo: {
                            trains,
                            filter: {
                                ticketType,
                                trainType,
                                depStation,
                                arrStation,
                            },
                        },
                    },
                } = result;

                dispatch(setTrainList(trains));
                dispatch(setTicketTypes(ticketType));
                dispatch(setTrainTypes(trainType));
                dispatch(setDepartStations(depStation));
                dispatch(setArriveStations(arrStation));
            });
    }, [
        from,
        to,
        departDate,
        highSpeed,
        searchParsed,
        orderType,
        onlyTickets,
        checkedTicketTypes,
        checkedTrainTypes,
        checkedDepartStations,
        checkedArriveStations,
        departTimeStart,
        departTimeEnd,
        arriveTimeStart,
        arriveTimeEnd,
    ]);
    //导航
    const { isPrevDisabled, isNextDisabled, prev, next } = useNav(
        departDate,
        dispatch,
        prevDate,
        nextDate
    );

    const bottomCbs = useMemo(() => {
        return bindActionCreators(
            {
                toggleOrderType,
                toggleHighSpeed,
                toggleOnlyTickets,
                toggleIsFiltersVisible,
                setCheckedTicketTypes,
                setCheckedTrainTypes,
                setCheckedDepartStations,
                setCheckedArriveStations,
                setDepartTimeStart,
                setDepartTimeEnd,
                setArriveTimeStart,
                setArriveTimeEnd,
            },
            dispatch
        );
    }, []);

    if (!searchParsed) {
        return null;
    }
    return (
        <div>
            <div className="header-wrapper">
                <Header title={`${from} ⇀ ${to}`} onBack={onBack} />
            </div>
            <Nav
                date={departDate}
                isPrevDisabled={isPrevDisabled}
                isNextDisabled={isNextDisabled}
                prev={prev}
                next={next}
            />
            <List list={trainList} />
            <Bottom
                highSpeed={highSpeed}
                orderType={orderType}
                onlyTickets={onlyTickets}
                isFiltersVisible={isFiltersVisible}
                ticketTypes={ticketTypes}
                trainTypes={trainTypes}
                departStations={departStations}
                arriveStations={arriveStations}
                checkedTicketTypes={checkedTicketTypes}
                checkedTrainTypes={checkedTrainTypes}
                checkedDepartStations={checkedDepartStations}
                checkedArriveStations={checkedArriveStations}
                departTimeStart={departTimeStart}
                departTimeEnd={departTimeEnd}
                arriveTimeStart={arriveTimeStart}
                arriveTimeEnd={arriveTimeEnd}
                {...bottomCbs}
            />
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        ...state.getIn(['query'])
        // from: state.getIn(['query', 'from']),
        // to: state.getIn(['query', 'to']),
        // trainList: state.getIn(['query', 'trainList']),
        // departDate: state.getIn(['query', 'departDate']),
        // highSpeed: state.getIn(['query', 'highSpeed']),
        // searchParsed: state.getIn(['query', 'searchParsed']),
        // orderType: state.getIn(['query', 'orderType']),
        // onlyTickets: state.getIn(['query', 'onlyTickets']),
        // isFiltersVisible: state.getIn(['query', 'isFiltersVisible']),
        // ticketTypes: state.getIn(['query', 'ticketTypes']),
        // trainTypes: state.getIn(['query', 'trainTypes']),
        // departStations: state.getIn(['query', 'departStations']),
        // arriveStations: state.getIn(['query', 'arriveStations']),
        // checkedTicketTypes: state.getIn(['query', 'checkedTicketTypes']),
        // checkedTrainTypes: state.getIn(['query', 'checkedTrainTypes']),
        // checkedDepartStations: state.getIn(['query', 'checkedDepartStations']),
        // checkedArriveStations: state.getIn(['query', 'checkedArriveStations']),
        // departTimeStart: state.getIn(['query', 'departTimeStart']),
        // departTimeEnd: state.getIn(['query', 'departTimeEnd']),
        // arriveTimeStart: state.getIn(['query', 'arriveTimeStart']),
        // arriveTimeEnd: state.getIn(['query', 'arriveTimeEnd']),
    }
}
const mapDispatchToProps = (dispatch) => {

    return { dispatch };
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Query);